package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mapper.AnalysisDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.mapper.UsersMapper;
import com.itheima.pojo.Admin;
import com.itheima.pojo.AnalysisDay;
import com.itheima.pojo.Log;
import com.itheima.pojo.Users;
import com.itheima.service.AdminService;
import com.itheima.service.SummaryInfoService;
import com.itheima.vo.AddActiveInfo;
import com.itheima.vo.SummaryInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SummaryInfoServiceImpl implements SummaryInfoService {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private LogMapper logMapper;
	@Autowired
    AnalysisDayMapper analysisDayMapper;
    @Autowired
    private AdminService adminService;
    @Override
    public SummaryInfo getSummaryInfo(String token) {


        //验证token
        Admin admin = adminService.queryUserByToken(token);

        if(admin==null){
            return null;
        }
        //构建查询累计用户
        QueryWrapper<Users> queryWrapper = new QueryWrapper();
        Integer integer = usersMapper.selectCount(queryWrapper);
        //新建SummaryInfo对象 讲数据赋值
        SummaryInfo summaryInfo = new SummaryInfo();
        summaryInfo.setCumulativeUsers(integer);
        //获取当前时间转化为标准格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd");
        String nowTime = simpleDateFormat.format(new Date());
        //构建查询,查询当天活跃用户数量
        QueryWrapper queryWrapperone = new QueryWrapper();
        queryWrapperone.select("DISTINCT user_id,id").eq("log_time",nowTime);
        Integer todayCount = logMapper.selectCount(queryWrapperone);
        //获取七天前的时间戳
        String weekTime = simpleDateFormat.format(new Date(new Date().getTime() - (24 * 60 * 60 * 1000*7)));
        //构建查询,查询七天内的活跃用户数量
        QueryWrapper wrapper01 = new QueryWrapper();
        wrapper01.select("DISTINCT user_id,id").between("log_time",weekTime,nowTime);
        Integer weekCount = logMapper.selectCount(wrapper01);
        //获取一个月前的时间戳
        String mounthTime = simpleDateFormat.format(new Date(new Date().getTime() - (24 * 60 * 60 * 1000*30)));
//        构建查询,查询一个月内的活跃用户数量
        QueryWrapper wrapper02 = new QueryWrapper();
        wrapper01.select("DISTINCT user_id,id").between("log_time",mounthTime,nowTime);
        Integer mounthCount = logMapper.selectCount(wrapper02);
        //将周活越数和月活跃数赋给summaryInfo对象
        summaryInfo.setActivePassWeek(weekCount);
        summaryInfo.setActivePassMonth(mounthCount);
        //获取昨天的时间戳
        String yesterdayTime = simpleDateFormat.format(new Date(new Date().getTime() - (24 * 60 * 60 * 1000)));
        //构建查询,查询昨天的活跃用户数量
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.select("DISTINCT user_id,id").eq("log_time",yesterdayTime);
        Integer yesterCount = logMapper.selectCount(wrapper1);

        //获取前天的时间戳
        String beforedayTime = simpleDateFormat.format(new Date(new Date().getTime() - (2*24 * 60 * 60 * 1000)));
        //构建查询,查询前天的活跃用户数量
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.select("DISTINCT user_id,id").eq("log_time",beforedayTime);
        Integer beforeCount = logMapper.selectCount(wrapper2);
        if(yesterCount==0){
            yesterCount=1;
        }
        if(beforeCount==0){
            beforeCount=1;
        }
        //将获取到的数据赋给summaryInfo对象
        summaryInfo.setActiveUsersToday(todayCount);
        summaryInfo.setActiveUsersTodayRate((todayCount+0.0-yesterCount)/yesterCount);
        summaryInfo.setActiveUsersYesterday(yesterCount);
        summaryInfo.setActiveUsersYesterdayRate((yesterCount+0.0-beforeCount)/beforeCount);

        QueryWrapper<Log> queryYesterdayUsers = new QueryWrapper<>();
        queryYesterdayUsers.select("user_id")
                .likeRight("created",yesterdayTime);
        Integer newUsersYesterday = logMapper.selectCount(queryYesterdayUsers);

        QueryWrapper<Log> queryTodayUsers = new QueryWrapper<>();
        queryTodayUsers.select("user_id")
                .likeRight("created",nowTime);
        Integer newUsersToday = logMapper.selectCount(queryTodayUsers);



        QueryWrapper<Log> queryYesterdayLogin = new QueryWrapper<>();
        queryYesterdayLogin.select("user_id")
                .eq("log_time",yesterdayTime);
        Integer loginTimesYesterday = logMapper.selectCount(queryYesterdayLogin);

        QueryWrapper<Log> queryTodayLogin = new QueryWrapper<>();
        queryTodayLogin.select("user_id")
                .eq("log_time",nowTime);
        Integer loginTimesToday = logMapper.selectCount(queryTodayLogin);

        double newUsersTodayRate = (newUsersToday - newUsersYesterday)+0.0 / newUsersYesterday * 100;
//        String newUsersTodayRateStr;
//        if (newUsersTodayRate < 0) {
//            newUsersTodayRateStr = "环比下降" + (-newUsersTodayRate) + "%";
//        } else {
//            newUsersTodayRateStr = "环比上升" + newUsersTodayRate + "%";
//        }

        double loginTimesTodayRate = (loginTimesToday - loginTimesYesterday)+0.0 / loginTimesYesterday * 100;
//        String loginTimesTodayRateStr;
//        if (loginTimesTodayRate < 0) {
//            loginTimesTodayRateStr = "环比下降" + (-loginTimesTodayRate) + "%";
//        } else {
//            loginTimesTodayRateStr = "环比上升" + loginTimesTodayRate + "%";
//        }


        summaryInfo.setNewUsersToday(newUsersToday);
        summaryInfo.setLoginTimesToday(loginTimesToday);
        summaryInfo.setNewUsersTodayRate(newUsersTodayRate);
        summaryInfo.setLoginTimesTodayRate(loginTimesTodayRate);
        //返回summaryInfo对象
        return summaryInfo;
    }
	//折线图
    //查询一段时间内用户活跃以及用户新增以及次日留存/K
    @Override
    public AddActiveInfo queryAddActive(String token, Map<String, String> param)  {
        //验证token
        Admin admin = adminService.queryUserByToken(token);

        if(admin==null){
            return null;
        }

        if(param.get("sd")==null||param.get("ed")==null){
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //开始时间
        Date startdate = null;
        Date enddate = null;
        try {

            //开始时间
            startdate = format.parse(param.get("sd"));//Sun Dec 29 00:00:00 CST 2019    Date

            //结束时间
            enddate = format.parse(param.get("ed"));


        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time = startdate.getTime();
        long time1 = enddate.getTime();
        long freetime = 31622400000L;
        if((time1-time)>=freetime||(time1-time)<0){

            return null;
        }
        //开始时间到最后时间额查询数据
        QueryWrapper<AnalysisDay> analysisDayWrapper = new QueryWrapper<>();
        //设置查询条件
        analysisDayWrapper.between("record_date", startdate, enddate);

        if(startdate.equals(enddate)){
            return null;
        }
        //查询
        // 数据到list
        List<AnalysisDay> analysis = analysisDayMapper.selectList(analysisDayWrapper);


        //101 新增 102 活跃用户 103 次日留存率
        Integer type = Integer.valueOf(param.get("type"));

        if (type.equals(101)) {
            //新增
            //获取数据库数据
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
            if (analysis != null) {

                ArrayList<String> list2 = new ArrayList<>();

                for (AnalysisDay analysisDay : analysis) {
                    Date recordDate = analysisDay.getRecordDate();
                    String format1 = format.format(recordDate);
                    list2.add(format1);
                }
                //排序list2
                Collections.sort(list2);
                //遍历排序好的list2,将日期和注册数量存入map
                for (String s : list2) {
                    System.out.println(s);
                    QueryWrapper<AnalysisDay> analysisDayQueryWrapper = new QueryWrapper<>();
                    QueryWrapper<AnalysisDay> record_dateOrder = analysisDayQueryWrapper.eq("record_date", s);
                    AnalysisDay analysisDay = analysisDayMapper.selectOne(record_dateOrder);
                    Integer numRegistered = analysisDay.getNumRegistered();
                    map.put(s, numRegistered);
                }



                ArrayList<String> list = new ArrayList<>();
                ArrayList<Integer> list1 = new ArrayList<>();
                if (map != null) {
                    //查询key和value
                    for (HashMap.Entry<String, Integer> stringIntegerEntry : map.entrySet()) {
                        String key = stringIntegerEntry.getKey();
                        Integer value = stringIntegerEntry.getValue();
                        System.out.println(key+"---------"+value);
                        //添加到list集合
                        list.add(key);
                        list1.add(value);
                    }
                    //创建对象
                    AddActiveInfo addActiveInfo = new AddActiveInfo();
                    //存入对象
                    addActiveInfo.setTitle(list);
                    addActiveInfo.setAmount(list1.toArray());
                    return addActiveInfo;
                }
                return null;
            }
            return null;

            //返回数据{
            //    "title": "[1, 2, 3, 4]",
            //    "amount": "[1, 2, 3, 4]"
            //}
        } else if (type == 102) {
            //活跃用户
            //获取数据库数据
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
            if (analysis != null) {

                ArrayList<String> list2 = new ArrayList<>();
                for (AnalysisDay analysisDay : analysis) {
                    //放入map中
                    Date recordDate = analysisDay.getRecordDate();
                    String recordtime = format.format(recordDate);
                    list2.add(recordtime);

                }
                Collections.sort(list2);
                for (String s : list2) {
                    QueryWrapper<AnalysisDay> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("record_date",s);
                    AnalysisDay analysisDay = analysisDayMapper.selectOne(queryWrapper);
                    Integer numActive = analysisDay.getNumActive();
                    map.put(s,numActive);
                }



                ArrayList<String> list = new ArrayList<>();
                ArrayList<Integer> list1 = new ArrayList<>();

                if (map != null) {
                    //查询key和value
                    for (HashMap.Entry<String, Integer> stringIntegerEntry : map.entrySet()) {
                        String key = stringIntegerEntry.getKey();
                        Integer value = stringIntegerEntry.getValue();
                        //添加到list集合
                        list.add(key);
                        list1.add(value);
                    }
                    //创建对象
                    AddActiveInfo addActiveInfo = new AddActiveInfo();
                    //存入对象
                    addActiveInfo.setTitle(list);
                    addActiveInfo.setAmount(list1.toArray());
                    return addActiveInfo;
                }
                return null;




            }
            return null;

        } else if (type == 103) {
            //次日留存率
            //获取数据库数据
            LinkedHashMap<String, Double> map = new LinkedHashMap<>();
            if (analysis == null) {
                return null;
            }

            ArrayList<String> list2 = new ArrayList<>();
            for (AnalysisDay analysisDay : analysis) {
                //放入map中
                Date recordDate = analysisDay.getRecordDate();
                String recordtime = format.format(recordDate);
                list2.add(recordtime);

            }
            Collections.sort(list2);
            //创建格式化对象
            DecimalFormat df = new DecimalFormat("0.00");

            for (String s : list2) {
                QueryWrapper<AnalysisDay> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("record_date",s);
                AnalysisDay analysisDay = analysisDayMapper.selectOne(queryWrapper);
                Integer numActive1 = analysisDay.getNumActive();
                Integer numRetention1d = analysisDay.getNumRetention1d();
                float v = (float) numRetention1d / numActive1;
                //格式化数量
                String format1 = df.format(v);
                //转成Double
                Double Retentiond = Double.valueOf(format1);


                map.put(s,Retentiond);
            }


            ArrayList<String> list = new ArrayList<>();
            ArrayList<Double> list1 = new ArrayList<>();

            if (map != null) {
                //查询key和value
                for (Map.Entry<String, Double> stringIntegerEntry : map.entrySet()) {
                    String key = stringIntegerEntry.getKey();
                    Double value = stringIntegerEntry.getValue();
                    //添加到list集合
                    list.add(key);
                    list1.add(value);
                }
                //创建对象
                AddActiveInfo addActiveInfo = new AddActiveInfo();
                //存入对象
                addActiveInfo.setTitle(list);
                addActiveInfo.setAmount(list1.toArray());
                return addActiveInfo;
            }
            return null;
        }
        else {
            return null;
        }

    }
}
